package com.nasa.spider.webmagic.example;

import com.nasa.spider.webmagic.pipeline.FilePipeline;
import com.nasa.spider.webmagic.pipeline.JsonFilePipeline;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.pipeline.ConsolePipeline;
import us.codecraft.webmagic.pipeline.ResultItemsCollectorPipeline;
import us.codecraft.webmagic.processor.PageProcessor;

import java.util.List;

/**
 * <p></p >
 *
 * @author youyoukele
 * @version 1.0
 * @date 2023/7/5 16:43
 */
public class OschinaBlogPageProcessor implements PageProcessor {

    @Override
    public void process(Page page) {
        List<String> links = page.getHtml().links().regex("http://my\\.oschina\\.net/flashsword/blog/\\d+").all();
        page.addTargetRequests(links);
        page.putField("content", page.getHtml().$("div.content").toString());
    }

    @Override
    public Site getSite() {
        return Site.me()
                .setDomain("my.oschina.net")
                .setRetrySleepTime(100)
                .setRetryTimes(3);
    }

    public static void main(String[] args) {
        ResultItemsCollectorPipeline resultItemsCollectorPipeline = new ResultItemsCollectorPipeline();
        Spider.create(new OschinaBlogPageProcessor())
                .addUrl("http://my.oschina.net/flashsword/blog")
                .addPipeline(new ConsolePipeline())
                .addPipeline(new FilePipeline("/Users/youyoukele/workspace/"))
                .addPipeline(new JsonFilePipeline("/Users/youyoukele/workspace/"))
                .addPipeline(resultItemsCollectorPipeline)
                .thread(5)
                .run();

        List<ResultItems> collected = resultItemsCollectorPipeline.getCollected();
        System.out.println(collected);
    }
}
